package jzqb.controller;

import haha.life.normal.FileUtil;
import haha.life.normal.FileuploadUtils;
import io.swagger.annotations.Api;
import jzqb.bo.ZTBo;
import jzqb.bo.ZTJBo;
import jzqb.bo.ZTWXBo;
import jzqb.common.Result;
import jzqb.service.ZTJService;
import jzqb.service.ZTWXService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.util.Collections;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/ztj")
@Api(tags = "专题集")
public class ZTJController {

    @Autowired
    ZTJService ztjService;

    @Autowired
    ZTWXService ztwxService;

    @Value("${filePath.ztjCoverPath}")
    private String ztjCoverPath;
    /**
     * 搜索专题集的result
     */
    @PostMapping("/searchResult")
    public Result getResultDetail(@RequestBody ZTJBo ztjBo) {
        Result result = ztjService.searchResult(ztjBo);
        return result;
    }
    /**
     * getZjtDetailById
     */
    @PostMapping("/getZjtDetailById")
    public Result getZjtDetailById(@RequestBody ZTJBo ztjBo) {
        ZTJBo ztjBoo = ztjService.getZjtDetailById(ztjBo);
        if (ztjBoo == null) {
            return Result.fail("无法查询到此专题");
        }
        List<ZTBo> ztjBos = ztjService.getZtList(ztjBo);
        if (ztjBos == null || ztjBos.size() == 0) {
            return Result.succ(ztjBoo);
        }
        Collections.sort(ztjBos);
        // 在对专题进行循环然后查询出每个专题下面的专题文献。

        for (ZTBo bo : ztjBos) {
            List<ZTWXBo> ztwxBos = ztwxService.getListByztBo(bo);
            if (ztwxBos != null && ztwxBos.size() > 0) {
                Collections.sort(ztwxBos);
            }
            bo.setZtwxBos(ztwxBos);
        }

        ztjBoo.setZtBos(ztjBos);
        return Result.succ(ztjBoo);
    }

    @GetMapping("/getPictureResource")
    public void getResultDetail(@PathParam("coverPage") String coverPage, HttpServletResponse response) {
        if ("".equals(coverPage) || coverPage == null) {
            return;
        }
        try {
            String path = FileUtil.calculateAbstractPath(coverPage, ztjCoverPath);
            FileuploadUtils.download(path, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
